package com.fbs.wowo.wx.service.imp;

import com.fbs.wowo.exception.DataOverflowException;
import com.fbs.wowo.exception.ErrorCode;
import com.fbs.wowo.util.common.ComUtils;
import com.fbs.wowo.wx.entity.WxAuth;
import com.fbs.wowo.wx.mapper.WxAuthMapper;
import com.fbs.wowo.wx.service.WxAuthService;
import com.fbs.wowo.wx.wxUtil.HttpUtils;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Transactional
public class WxAuthServiceImp implements WxAuthService {


    @Resource
    private WxAuthMapper wxAuthMapper;


    @Override
    public List<WxAuth> findWxAuthByUserId(String userId) {
        return wxAuthMapper.findWxAuthByUserId(userId);
    }

    @Override
    public int insertSelective(WxAuth record) {
        WxAuth wxAuth = wxAuthMapper.findWxAuthState(record.getUserId(), record.getWxArticleId());
        if (wxAuth!=null){
            throw new DataOverflowException(ErrorCode.ERR_DATA_HAS_EXIST);
        }
        record.setId(ComUtils.getUUID());
        record.setCreateDt(new Date());
        record.setUpdateDt(new Date());
        record.setState((byte)3);       //处理中

        String url ="http://127.0.0.1:8888/bale";
        Map<String, String> map = new HashMap<>();
        map.put("cmdId", record.getId());
        map.put("content",record.getContent() );
        map.put("url",record.getWxArticleAddress());
        JSONObject jsonParam = JSONObject.fromObject(map);
        String data = HttpUtils.post(url, jsonParam.toString());
        System.out.println("data:"+data);

        JSONObject json = JSONObject.fromObject(data);

        if (json.containsKey("msg")) {
            if (json.get("msg").equals("success")){
                return wxAuthMapper.insertSelective(record);
            }
        }
        throw new DataOverflowException(ErrorCode.ERR_SEND_PACK);
    }

    @Override
    public int updateByPrimaryKeySelective(WxAuth record) {
        return wxAuthMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public WxAuth selectByPrimaryKey(String id) {
        return wxAuthMapper.selectByPrimaryKey(id);
    }


}
